/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SharedPrefsCookiePersistor.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.cookie.persistentcookiejar.persistence;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import io.bhex.sdk.config.bean.BackupDomainBean;
import io.bhex.sdk.config.domain.BackupDomainManager;
import okhttp3.Cookie;

@SuppressLint("CommitPrefEdits")
public class SharedPrefsCookiePersistor implements CookiePersistor {

    private final SharedPreferences sharedPreferences;
    private Application mContext;

    public SharedPrefsCookiePersistor(Application context) {
        this(context.getSharedPreferences("CookiePersistence", Context.MODE_PRIVATE));
        mContext = context;
    }

    public SharedPrefsCookiePersistor(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }

    @Override
    public List<Cookie> loadAll() {
        List<Cookie> cookies = new ArrayList<>(sharedPreferences.getAll().size());

        for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) {
            String serializedCookie = (String) entry.getValue();

//            Cookie cookie = new SerializableCookie().decode(serializedCookie);
//            if (cookie != null) {
//                cookies.add(cookie);
//            }

            Cookie cookie = new SerializableCookie().decode(serializedCookie);
            if (cookie != null) {
                List<BackupDomainBean> backupDomainList = BackupDomainManager.getInstance().getBackupDomainList();
                if (backupDomainList != null && backupDomainList.size()>0) {
                    //TODO 有备用域名，给备用域名写入cookie
//                    DebugLog.e("COOKIE-WRITE","share cache 写入cookie " + cookie.name());
                    for (BackupDomainBean backupDomainBean : backupDomainList) {
                        if (backupDomainBean != null) {
                            String domain = backupDomainBean.getDomain();
                            if (!TextUtils.isEmpty(domain)) {

                                Cookie newCookie = new Cookie.Builder()
                                        .domain(domain)
                                        .expiresAt(cookie.expiresAt())
                                        .name(cookie.name())
                                        .value(cookie.value())
                                        .build();
                                if (newCookie != null) {
                                    cookies.add(newCookie);
                                }
                            }
                        }

                    }

                }else{
                    cookies.add(cookie);
                }
            }
        }
        return cookies;
    }

    @Override
    public void saveAll(Collection<Cookie> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (Cookie cookie : cookies) {
            editor.putString(createCookieKey(cookie), new SerializableCookie().encode(cookie));
//            DebugLog.e("Cookie",createCookieKey(cookie)+"    >>><<<    "+new SerializableCookie().encode(cookie));
        }
//        editor.commit();
        editor.apply();
        //TODO 触发更新域名列表的cookie
//        DebugLog.e("COOKIE-001-shared","cookie size "+cookies.size());
//        CookieUtils.setDomainsCookies(mContext,BackupDomainManager.getInstance().getBackupDomainList());
    }

    @Override
    public void removeAll(Collection<Cookie> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (Cookie cookie : cookies) {
            editor.remove(createCookieKey(cookie));
        }
//        editor.commit();
        editor.apply();
    }

    private static String createCookieKey(Cookie cookie) {
//        return (cookie.secure() ? "https" : "http") + "://" + cookie.domain() + cookie.path() + "|" + cookie.name();
        return (cookie.name());
    }

    @Override
    public void clear() {
//        sharedPreferences.edit().clear().commit();
        sharedPreferences.edit().clear().apply();
    }
}
